package com.dwjm.shop.HSh.goods;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

@WebServlet("/updateGoods")

public class UpdateGoodsHandler extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        try {
            // 参数解析与校验
            Goods goods = parseGoodsFromRequest(req);
            // 参数有效性验证
            if(goods.getId() == null) {
                sendErrorResponse(resp, "商品ID不能为空");
                return;
            }
            GoodsDao goodsDao = new GoodsDaoImpl();
            int result = goodsDao.updateGoods(goods);

            resp.getWriter().write(result > 0 ? "Y" : "N");

        } catch (NumberFormatException e) {
            sendErrorResponse(resp, "参数格式错误：" + e.getMessage());
        } catch (Exception e) {
            sendErrorResponse(resp, "系统错误：" + e.getMessage());
        }
    }

    private Goods parseGoodsFromRequest(HttpServletRequest req) {
        Goods goods = new Goods();
        try {
            // 必填字段
            goods.setId(Integer.parseInt(req.getParameter("id")));
            goods.setTitle(req.getParameter("title"));
            goods.setPrice(new BigDecimal(req.getParameter("price")));

            // 选填字段
            goods.setDescr(req.getParameter("descr"));
            goods.setImg(req.getParameter("img"));

            // 关联字段
            String mid = req.getParameter("mid");
            if(mid != null && !mid.isEmpty()) {
                goods.setMid(Integer.parseInt(mid));
            }
        } catch (NumberFormatException e) {
            throw new RuntimeException("数值转换异常：" + e.getMessage());
        }
        return goods;
    }

    private void sendErrorResponse(HttpServletResponse resp, String message)
            throws IOException {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().write("E:" + message);
    }
}